<template>
	<view class="preview-view">
		<swiper class="swiper" circular :current="currentIndex" @change="swiperChange">
			<swiper-item v-for="(item,index) in wallListData" :key="item._id">
				<image v-if="index === currentIndex || index === currentIndex - 1 || index === currentIndex + 1"
					:src="item.picUrl" class="picture" mode="aspectFill" @click="maskChange"></image>
			</swiper-item>
		</swiper>
		<view v-if="maskState" class="mask">
			<view class="go-back" :style="{top:statusBarHeight + 'px'}" @click="goBack">
				<uni-icons type="left" color="#fff" size="30rpx"></uni-icons>
			</view>
			<view class="count">
				{{ currentIndex + 1 }}/ {{ wallListData.length }}
			</view>
			<view class="time">
				<uni-dateformat :date="new Date()" format="hh:mm"></uni-dateformat>
			</view>
			<view class="date">
				<uni-dateformat :date="new Date()" format="MM月dd日"></uni-dateformat>
			</view>
			<view class="footer">
				<view class="box-item" @click="handleInfo">
					<uni-icons type="info" size="36rpx"></uni-icons>
					<text class="text">信息</text>
				</view>
				<view class="box-item" @click="handleScore">
					<uni-icons type="star" size="36rpx"></uni-icons>
					<text class="text">{{ currentWall.score }}分</text>
				</view>
				<view class="box-item" @click="handleDownload">
					<uni-icons type="download" size="36rpx"></uni-icons>
					<text class="text">下载</text>
				</view>
			</view>
		</view>
		<uni-popup ref="popup" type="bottom" background-color="#fff" border-radius="10px 10px 0 0">
			<view class="popup-content">
				<div class="header">
					<view></view>
					<view class="title">
						壁纸信息
					</view>
					<view class="icon" @click="onPopupClose">
						<uni-icons type="closeempty"></uni-icons>
					</view>
				</div>
				<scroll-view scroll-y class="scroll-box">
					<view class="info">
						<view class="row">
							<view class="label">
								壁纸ID：
							</view>
							<text selectable class="value">{{ currentWall._id }}</text>
						</view>
						<view class="row">
							<view class="label">
								发布者：
							</view>
							<text selectable class="value">{{ currentWall.nickname }}</text>
						</view>
						<view class="row">
							<view class="label">
								评分：
							</view>
							<view class="value rate-box">
								<uni-rate readonly :touchable="false" size="16" :value="currentWall.score" />
								<text class="score">{{ currentWall.score }}</text>
							</view>
						</view>
						<view class="row">
							<view class="label">
								摘要：
							</view>
							<view class="value">
								{{ currentWall.description }}
							</view>
						</view>
						<view class="row">
							<view class="label">
								标签：
							</view>
							<view class="value tabs-box">
								<view class="tab" v-for="item in currentWall.tabs" :key="item">
									{{ item }}
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
				<view class="copyright">
					声明：本图片来自用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台，邮箱513894357@qq.com，管理将删除侵权壁纸，维护您的权益。
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="scorePopup" :is-mask-click="false" background-color="#fff" border-radius="30rpx">
			<view class="score-content">
				<view class="header">
					<view></view>
					<view class="title">
						壁纸信息
					</view>
					<view class="icon" @click="onScoreClose">
						<uni-icons type="closeempty"></uni-icons>
					</view>
				</view>
				<view class="handle-bar">
					<uni-rate v-model="score" allowHalf />
					<text class="score">{{ score }}分</text>
				</view>
				<view class="score-footer">
					<button type="default" class="button" :disabled="!score" @click="onSubmit">确认评分</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		getCurrentWall,
		submitScore,
		writeWallDownload
	} from '@/api/requestInterface.js'

	import {
		useSystemInfo
	} from '@/utils/system.js'

	// 使用pinia 管理数据缓存
	import {
		useWallListStore
	} from '@/stores/wallList.js'
	const wallList = useWallListStore()

	const maskState = ref(true) // 控住状态显示
	const popup = ref(null) // 弹窗实例
	const scorePopup = ref(null) // 评分弹窗实例
	const score = ref(0) // 评分分数
	const wallListData = ref([]) // 壁纸列表
	const currentWall = ref({}) // 当前壁纸信息
	const currentIndex = ref(0) // 当前壁纸下标

	const {
		statusBarHeight,
	} = useSystemInfo() // 系统信息hooks

	// 获取pinia缓存数据并转换图片
	wallListData.value = wallList.wallTable.map(item => {
		return {
			...item,
			picUrl: item.smallPicurl.replace('_small.webp', '.jpg')
		}
	})

	// function
	// 返回上一页
	const goBack = () => {
		uni.navigateBack({
			fail: () => {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		})
	}

	// 图片触碰事件
	const maskChange = () => {
		maskState.value = !maskState.value
	}

	// 信息按钮点击事件
	const handleInfo = () => {
		popup.value.open()
	}

	// 壁纸详情弹窗关闭
	const onPopupClose = () => {
		popup.value.close()
	}

	// 评分弹窗操作
	const handleScore = () => {
		score.value = currentWall.value.score
		scorePopup.value.open()
	}

	// 关闭评分操作弹窗
	const onScoreClose = () => {
		scorePopup.value.close()
		score.value = 0
	}

	// 评分提交
	const onSubmit = async () => {
		const submitScoreNum = score.value
		const {
			errCode
		} = await submitScore({
			classid: currentWall.value.classid,
			wallId: currentWall.value._id,
			userScore: submitScoreNum
		})
		if (errCode === 0) {
			uni.showToast({
				title: '评分成功',
				icon: 'none',
				duration: 1000,
				complete() {
					onScoreClose()
				}
			})
			wallListData.value[currentIndex.value].score = submitScoreNum
			currentWall.value.score = submitScoreNum
			wallList.updateData(wallListData.value)
		}
	}


	// 加载当前壁纸信息
	const loadCurrentWall = async (id) => {
		const {
			errCode,
			data
		} = await getCurrentWall({
			id: id
		})

		if (errCode === 0) {
			currentWall.value = {
				...data[0],
				picUrl: data[0].smallPicurl.replace('_small.webp', '.jpg')
			}
		} else {
			currentWall.value = {}
		}
	}

	// 轮播图change事件
	const swiperChange = (e) => {
		currentIndex.value = e.detail.current
		loadCurrentWall(wallListData.value[currentIndex.value]._id)
	}

	// 图片下载
	const handleDownload = async () => {
		// #ifdef H5
		uni.showModal({
			content: '请长按保存壁纸',
			showCancel: false
		})
		// #endif

		// #ifndef H5
		uni.showLoading({
			title: '下载中',
			mask: false
		})
		try {
			const {
				errCode,
				errMsg
			} = await writeWallDownload({
				classid: currentWall.value.classid,
				wallId: currentWall.value._id,
			})
			if (errCode !== 0) throw errMsg

			uni.getImageInfo({
				src: currentWall.value.picUrl,
				success(res) {

					uni.saveImageToPhotosAlbum({
						filePath: res.path,
						success(resulet) {
							console.log(resulet);
						},
						fail(err) {
							if (err.errMsg === 'saveImageToPhotosAlbum:fail cancel') {
								uni.showToast({
									title: '保存失败，请重新点击下载',
									icon: 'none'
								})

								return
							}
							uni.showModal({
								title: '提示',
								content: '需要授权保存相册',
								success(res) {
									if (res.confirm) {
										uni.openSetting({
											success: (setting) => {
												if (setting.authSetting[
														'scope.writePhotosAlbum'
													]) {
													uni.showToast({
														title: '获取授权成功',
														icon: 'none'
													});
												} else {
													uni.showToast({
														title: '获取授权失败',
														icon: 'none'
													});
												}
											}
										})
									}
								}
							})
						},
						complete() {
							uni.hideLoading()
						}
					})
				},
				fail(err) {
					console.log('error=>>', err);
				}
			})
		} catch {
			uni.hideLoading()
		}

		// #endif
	}

	// 生命周期
	onLoad((e) => {
		currentIndex.value = wallListData.value.findIndex(item => item._id === e.id)
		loadCurrentWall(e.id)
	})

	// 分享
	onShareAppMessage((e) => {
		return {
			title: '壁纸',
			path: `/pages/preview/preview?id=${currentWall.value._id}`
		}
	})

	// 分享朋友圈
	onShareTimeline(() => {
		return {
			title: '壁纸',
			query: `id=${currentWall.value._id}`
		}
	})
</script>

<style lang="scss" scoped>
	.preview-view {
		width: 100%;
		height: 100vh;
		position: relative;

		.swiper {
			width: 100%;
			height: 100%;
		}

		.mask {

			&>view {
				position: absolute;
				left: 0;
				right: 0;
				margin: auto;
				color: #fff;
			}

			.go-back {
				left: 10rpx;
				width: 48rpx;
				height: 48rpx;
				border-radius: 50%;
				border: 1px solid rgba(255, 255, 255, .5);
				margin: 0;
				text-align: center;
				background-color: rgba(0, 0, 0, .5);
				backdrop-filter: blur(10rpx);
				display: flex;
				align-items: center;
				justify-content: center;

			}

			.count {
				top: 10vh;
				width: fit-content;
				background-color: rgba(0, 0, 0, .3);
				font-size: 26rpx;
				padding: 3rpx 20rpx;
				border-radius: 20rpx;
				backdrop-filter: blur(10rpx);
			}

			.time {
				width: fit-content;
				font-size: 120rpx;
				top: calc(10vh + 40rpx);
				text-shadow: 0 4rpx rgba(0, 0, 0, .3);
			}

			.date {
				width: fit-content;
				color: #fff;
				font-size: 26rpx;
				top: calc(10vh + 180rpx);
				text-shadow: 0 4rpx rgba(0, 0, 0, .3);
			}

			.footer {
				bottom: 10vh;
				width: 60vw;
				background-color: #ede6e0;
				display: flex;
				justify-content: space-around;
				padding: 10rpx 15rpx;
				border-radius: 60rpx;
				color: $text-color;

				.box-item {
					display: flex;
					flex-direction: column;
					cursor: pointer;
					padding: 0 10rpx;

					.text {
						margin-top: 10rpx;
						font-size: 24rpx;
					}
				}
			}
		}

		.popup-content {
			padding: 15rpx;

			.header {
				display: flex;
				justify-content: space-between;
				color: $text-assist-color;

				.title {
					font-size: 26rpx;
				}

				:deep() {

					.uni-icons {
						color: $text-assist-color !important;
					}
				}
			}

			.scroll-box {
				max-height: 60vh;

				.info {
					.row {
						display: flex;
						padding: 16rpx 0;
						font-size: 32rpx;
						line-height: 1.7rem;

						.label {
							color: $text-assist-color;
							width: 140rpx;
							text-align: right;
							font-size: 28rpx;
						}

						.value {
							flex: 1;
							width: 0;
						}

						.rate-box {
							display: flex;
							align-items: center;
						}

						.tabs-box {
							display: flex;
							flex-wrap: wrap;

							.tab {
								border: 1rpx solid $brand-theme-color;
								color: $brand-theme-color;
								font-size: 22rpx;
								padding: 10rpx 30rpx;
								border-radius: 40rpx;
								line-height: 1em;
								margin: 0 10rpx 10rpx 0;
							}
						}
					}
				}
			}

			.copyright {
				font-size: 28rpx;
				padding: 20rpx;
				background: #f6f6f6;
				color: #666;
				border-radius: 10rpx;
				margin: 20rpx 0;
				line-height: 1.6em;
			}
		}

		.score-content {
			padding: 30rpx;
			width: 65vw;

			.header {
				display: flex;
				justify-content: space-between;
				color: $text-assist-color;

				.title {
					font-size: 26rpx;
				}

				:deep() {

					.uni-icons {
						color: $text-assist-color !important;
					}
				}
			}

			.handle-bar {
				display: flex;
				justify-content: center;
				align-items: center;
				margin: 30rpx 0;

				.score {
					color: #ffcb41;
					padding-left: 15rpx;
				}
			}

			.score-footer {
				text-align: center;
				margin-top: 30rpx;

				.button {
					background-color: #fff;
					border: 1px solid #000;
					color: #000;
					width: 200rpx;
					font-size: 24rpx;
					padding: 0 5rpx;

					&::after {
						border: none;
					}
				}
			}
		}
	}
</style>